<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/2
 * Time: 10:23
 */

namespace app\api\service;

use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use app\api\service\OrderService;
use app\api\model\Product;
/**
 * Class WxNotify
 * @package app\api\service
 * 微信回调方法处理类
 * 入口为handle函数
 * 处理函数为NotifyProcess 由子类重写
 */
Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class WxNotify extends \WxPayNotify
{
//    protected $data = <<<EOD
//<xml><appid><![CDATA[wxaaf1c852597e365b]]></appid>
//<bank_type><![CDATA[CFT]]></bank_type>
//<cash_fee><![CDATA[1]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1392378802]]></mch_id>
//<nonce_str><![CDATA[k66j676kzd3tqq2sr3023ogeqrg4np9z]]></nonce_str>
//<openid><![CDATA[ojID50G-cjUsFMJ0PjgDXt9iqoOo]]></openid>
//<out_trade_no><![CDATA[A301089188132321]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[944E2F9AF80204201177B91CEADD5AEC]]></sign>
//<time_end><![CDATA[20170301030852]]></time_end>
//<total_fee>1</total_fee>
//<trade_type><![CDATA[JSAPI]]></trade_type>
//<transaction_id><![CDATA[4004312001201703011727741547]]></transaction_id>
//</xml>
//EOD;

    public function NotifyProcess($data,&$msg){
        if($data['return_code']=='SUCCESS'){
            $orderNO = $data['out_trade_no'];
            try{
                Db::startTrans();
                $order = \app\api\model\Order::where('order_no',$orderNO)->find();
                if($order->status==1){
                    $orderService = new OrderService();
                    $status = $orderService->checkOrderStock($order->id);
                    if($status['pass']){
                        $this->reduceStock($status);
                        $this->updateStatus($order->id);
                    }else{
                        $this->updateStatus($order->id,false);
                    }
                }
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                return false;
            }
        }
        return;
    }

    public function reduceStock($status){
        foreach ($status as $product){
            Product::where('id',$product['id'])
                ->setDec('stock', $status['count']);
        }
    }

    public function updateStatus($orderid,$success=true){
        $status = $success==true?OrderStatusEnum::PAID:OrderStatusEnum::PAID_BUT_OUT_OF;
        \app\api\model\Order::where('id',$orderid)
            ->update(['status'=>$status]);
    }

}